package com.wfw.feichat.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author: wfw
 * @date: 2019-05-21 16:31
 */
public class WsServerIntializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {

        ChannelPipeline channelPipeline = socketChannel.pipeline();

        //websocket基于http协议，所以要有http编解码器
        channelPipeline.addLast(new HttpServerCodec());
        //对写大数据流的支持
        channelPipeline.addLast(new ChunkedWriteHandler());
        //对httpMessage进行聚合，几乎在netty中对编程都会用到此handler
        channelPipeline.addLast(new HttpObjectAggregator(1024 * 24));

        /**
         * websocket服务器处理的协议，用于指定给客户端连接访问的路由：/ws
         * 帮助处理一些复杂的事，handshaking(close,ping,pong)
         * 对于websocket来说，都是以frames进行传输的，不同的数据类型对应的frames也不同
         */
        channelPipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        channelPipeline.addLast(new ChatHandler());
    }
}
